#include "overlaywidget.h"
#include <QPainter>
#include <qevent.h>
#include <QDateTime>
#include <QOpenGLWidget>
#include <QOpenGLFunctions>
#include <qthread.h>
#include <QMenu>
#include <QAction>
#include "remotecallthread.h"
#include <Windows.h>
#include <WinUser.h>
#define KEY_DOWN(VK_NONAME) ((GetAsyncKeyState(VK_NONAME) & 0x8000) ? 1:0)
#define KEY_UP(VK_NONAME) ((GetKeyState(VK_NONAME) & 0x80) ? 1:0)
typedef BOOL(*SetCursorPos_DLL)(_In_ int X, _In_ int Y);
SetCursorPos_DLL _SetCursorPos=nullptr;
#pragma comment(lib, "OpenGL32.lib")

OverlayWidget::OverlayWidget(QWidget* parent)
    : QOpenGLWidget(parent)
{
    // 关键设置顺序：先设置窗口属性再设置焦点策略
    setAttribute(Qt::WA_TranslucentBackground);
    setAttribute(Qt::WA_AlwaysStackOnTop);

    // 强制启用键盘输入（关键修复！）
    setFocusPolicy(Qt::StrongFocus);
    setFocus(); // 主动获取焦点

    // 新增：禁用输入穿透（重要！）
    setWindowFlags(windowFlags() | Qt::WindowDoesNotAcceptFocus);

    // 启用双缓冲（默认已启用，此处显式确认）
    setAttribute(Qt::WA_AlwaysStackOnTop);
    setAttribute(Qt::WA_TranslucentBackground);

    // 设置刷新频率（fps）
    connect(&m_refreshTimer, &QTimer::timeout, this, &OverlayWidget::updateContent);
    m_refreshTimer.start(fps);
    // 创建并启动工作线程
    m_thread = new RemoteCallThread();
    m_thread->start();

    // 计时器，计算帧率
    m_fpsTimer.start();

    // 禁用垂直同步
    QSurfaceFormat format;
    format.setSwapInterval(0); // 0=禁用VSync, 1=启用
    format.setRenderableType(QSurfaceFormat::OpenGL);
    QSurfaceFormat::setDefaultFormat(format);

    HANDLE hHandle = GetModuleHandleA("user32.dll");
    if (hHandle == 0) return;
    _SetCursorPos = (SetCursorPos_DLL)GetProcAddress((HMODULE)hHandle, "SetCursorPos");
    CloseHandle(hHandle);
}

OverlayWidget::~OverlayWidget()
{
    // 安全停止线程
    if (m_thread) {
        m_thread->stop();
        delete m_thread;
    }
}

void OverlayWidget::initializeGL() {
    QOpenGLWidget::initializeGL();
    // 设置透明清除颜色
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}

static float boxX,boxY,boxY1,blood_full,blood,s,head_x1,head_y1,px1,px2,py1,py2;
static int roleId, isBot, radius;
int nameWidth, nameX, textWidth, textX;
void OverlayWidget::paintGL() {
    // 清除前帧内容（关键！）
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // 更新帧率统计
    updateFPS();

    // 使用QPainter绘制
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    // 绘制帧率
    // 在绘制代码前添加以下设置
    QFont font("微软雅黑", 12);
    font.setBold(true);
    font.setWeight(QFont::Black);
    painter.setFont(font);
    painter.setPen(Qt::green);
    painter.drawText(rect().adjusted(width()/2-100,20,-10,-30), Qt::AlignLeft | Qt::AlignTop,
                     QString("FPS: %1(%2)").arg(m_currentFPS, 5, 'f', 1).arg(connect_text));
    // ================== 自瞄相关变量初始化 ==================
    float center_x = width()/2.0f;   // 屏幕中心X
    float center_y = height()/2.0f;  // 屏幕中心Y
    float minDistance = FLT_MAX;     // 最小距离（初始值设为极大值）
    QPointF nearestTarget(0, 0);     // 最近的目标位置
    bool targetFound = false;         // 是否找到目标
    // 获取线程数据
    QString data = m_thread->getData();
    if (!data.isEmpty()) {
        QStringList sl_all = data.split(";");
        connect_text = "附近敌人"+QString::number(sl_all.size());
        for (int i = 0; i < sl_all.size(); ++i) {
            QStringList sl_item = sl_all[i].split(",");
            if(sl_item.size()!=10) continue;
            int index = 0;
            boxX = sl_item[index++].toFloat();
            boxY = sl_item[index++].toFloat();
            boxY1 = sl_item[index++].toFloat();
            blood = sl_item[index++].toFloat();
            if (std::isnan(blood)) {blood = 0;}
            blood_full =sl_item[index++].toFloat();
            if (std::isnan(blood_full)) {blood_full = 0;}
            s = sl_item[index++].toFloat();
            isBot = sl_item[index++].toInt();
            roleId = sl_item[index++].toInt();
            QString str_name=sl_item[index++];
            QStringList str_bones=sl_item[index++].split("|");
            QByteArray arr_data = QByteArray::fromHex(str_name.toUtf8());
            // 转换为UTF-16指针（假设原始数据是小端序）
            const char16_t *utf16Data = reinterpret_cast<const char16_t*>(arr_data.constData());
            // 找到第一个零终止符的位置
            int validLength = 0;
            while (validLength < 34 && utf16Data[validLength] != 0) {
                ++validLength;
            }
            if(validLength==0) continue;
            QString roleName = QString::fromUtf16(utf16Data, validLength);
            float hTmp=(boxY1-boxY);
            hTmp=(hTmp<30)?30:hTmp;
            float wTmp=hTmp/2;
            // 方框
            painter.setPen(Qt::white);
            painter.drawRect(boxX-wTmp/2, boxY1-hTmp/2, wTmp, hTmp);
            // 昵称和距离
            QString name=isBot?"Bot":roleName;
            QFontMetrics fm(painter.font());
            nameWidth = fm.horizontalAdvance(name);
            nameX = boxX - nameWidth / 2;
            painter.drawText(nameX, boxY1 - hTmp/2 - 25, name);
            QString text="["+QString::number(roleId)+"]"+QString::number(s, 'f', 1)+"m";
            text+=QString::number(blood, 'f', 2);
            textWidth = fm.horizontalAdvance(text);
            textX = boxX - textWidth / 2;
            painter.drawText(textX, boxY1 - hTmp/2 - 5, text);
            // 血量
            if(blood_full>0){
                painter.drawLine(boxX-wTmp/2, boxY1-hTmp/2, boxX-wTmp/2, boxY1+hTmp/2);
                painter.setPen(blood < 30 ? Qt::red : (blood < 75 ? Qt::blue : Qt::green));
                painter.drawLine(boxX-wTmp/2, boxY1-hTmp/2+hTmp-hTmp*blood/blood_full, boxX-wTmp/2,  boxY1+hTmp/2);
            }
            // 骨骼
            if(str_bones.size()!=15) continue;
            foreach (auto &item_bone, str_bones) {
                QStringList coords = item_bone.split(":");
                if(coords.size()==2){
                    head_x1 = coords[0].toFloat();
                    head_y1 = coords[1].toFloat();
                    radius  = 135/s;
                    if(radius<1) radius=1;
                    if(radius>25) radius=25;
                    float dx = head_x1 - center_x;
                    float dy = head_y1 - center_y;
                    float distance = sqrt(dx*dx + dy*dy);
                    if(minDistance>distance && distance<m_aimSettings.maxDistance){
                        minDistance = distance;
                        nearestTarget = {head_x1, head_y1};
                        targetFound = true;
                    }
                    painter.drawEllipse(QPoint(head_x1, head_y1), radius, radius);
                }else if(coords.size()==4){
                    px1 = coords[0].toFloat();
                    py1 = coords[1].toFloat();
                    px2 = coords[2].toFloat();
                    py2 = coords[3].toFloat();
                    painter.drawLine(px1, py1, px2, py2);
                }
            }
        }
        if (KEY_DOWN(1)){
            painter.drawEllipse(QPoint(center_x, center_y), m_aimSettings.maxDistance, m_aimSettings.maxDistance);
            if(targetFound) AimMove(nearestTarget.x()-center_x, nearestTarget.y()-center_y, minDistance);
        }
    }while(0);
}

void OverlayWidget::resizeGL(int w, int h) {
    // 更新视口
    glViewport(0, 0, w, h);
    // 更新线程中的窗口尺寸
    if (m_thread) {
        m_thread->setSize(w, h);
    }
}

void OverlayWidget::keyReleaseEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Home) {
        event->accept(); // 标记事件已处理
    } else {
        QOpenGLWidget::keyReleaseEvent(event); // 其他按键交给父类
    }
}

void OverlayWidget::updateContent() {
    update(); // 触发OpenGL重绘
}

void OverlayWidget::updateFPS() {
    m_frameCount++;

    // 每500ms计算一次实际帧率
    const qint64 elapsed = m_fpsTimer.elapsed();
    if(elapsed >= 500) {
        m_currentFPS = m_frameCount * 1000.0 / elapsed;
    }
}

// ================== 自瞄核心函数 ==================
void OverlayWidget::AimMove(int x_off, int y_off, float &s) {
    // 检查移动是否必要（死区机制）
    const float maxOffset = 2.0f;  // 偏移量小于2像素不移动
    if (s < maxOffset) {
        return;
    }
    float dx = x_off / m_aimSettings.smoothness;
    float dy = y_off / m_aimSettings.smoothness;
    int max_off = 2;
    if(dx>max_off) dx=max_off;
    if(dx<-max_off) dx=-max_off;
    if(dy>max_off) dy=max_off;
    if(dy<-max_off) dy=-max_off;
    POINT cursorPos;
    ::GetCursorPos(&cursorPos);
    int newX = cursorPos.x + static_cast<int>(dx);
    int newY = cursorPos.y + static_cast<int>(dy);
    if(_SetCursorPos) SetCursorPos(newX, newY);
}
